package com.jingxing.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.jingxing.mapper.UserInfoMapper;
import com.jingxing.pojo.UserInfo;
import com.jingxing.service.LoginService;
import com.jingxing.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 登录服务实现类
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 登录
     * @param phone
     * @param code
     * @return
     */
    @Override
    public String login(String phone, String code) {
        QueryWrapper<UserInfo> queryWrapperUserInfo = new QueryWrapper<>();
        queryWrapperUserInfo.eq("phone",phone);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapperUserInfo);
        if(userInfo==null){
            return "未报名";
        }
        Object redisCode = redisTemplate.boundValueOps(phone).get();
        if(redisCode==null){
            return "验证码过期";
        }

        if(!code.equals(redisCode.toString())){
            return "验证码错误";
        }else {
            userInfo.setSalt(code);
            userInfoMapper.updateById(userInfo);
        }

        String token = getToken(userInfo.getPhone(),userInfo.getSalt());
        redisTemplate.opsForValue().set(userInfo.getId().toString(),token,1, TimeUnit.DAYS);
        return token;

    }

    /**
     * 退出
     * @param request
     */
    @Override
    public void logout(HttpServletRequest request) {
        // 删除Redis缓存信息
        redisTemplate.delete(JWT.decode(JwtUtil.getToken(request)).getAudience().get(0));
    }

    /**
     * 根据token获取登录用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfo getLoginInfo(String token) {
        List<String> audience = JWT.decode(token).getAudience();
        String playerId = audience.get(0);
        UserInfo userInfo = userInfoMapper.selectById(playerId);
        return userInfo;
    }

    /**
     * 获取TOKEN
     * @param phone
     * @param salt
     * @return
     */
    private String getToken(String phone, String salt) {
        String token= JWT.create().withAudience(phone)
                .sign(Algorithm.HMAC256(salt));
        return token;
    }
}
